package main

import (
	"log"
	"net/http"
	"os"
	"yoga/config"
	"yoga/database"
	"yoga/graph"
	"yoga/identify"
	"yoga/network"

	"github.com/99designs/gqlgen/graphql/handler"
	"github.com/99designs/gqlgen/graphql/handler/extension"
	"github.com/99designs/gqlgen/graphql/handler/lru"
	"github.com/99designs/gqlgen/graphql/handler/transport"
	"github.com/vektah/gqlparser/v2/ast"
)

const defaultPort = "8080"

func init() {
	log.Println("执行init程序序列")
	config.InitConfig()
	database.InitDatabase()
	identify.InitToken()
}

func main() {
	port := os.Getenv("PORT")
	if port == "" {
		port = defaultPort
	}

	srv := handler.New(graph.NewExecutableSchema(graph.Config{Resolvers: &graph.Resolver{}}))

	srv.AddTransport(transport.Options{})
	srv.AddTransport(transport.GET{})
	srv.AddTransport(transport.POST{})

	srv.SetQueryCache(lru.New[*ast.QueryDocument](1000))

	srv.Use(extension.Introspection{})
	srv.Use(extension.AutomaticPersistedQuery{
		Cache: lru.New[string](100),
	})

	http.Handle("/graph", network.TokenIdentify(srv))
	http.HandleFunc("/api/weixinGetToken", network.WeixinGetTokenHandler)
	http.HandleFunc("/api/requestToken", network.RequestTokenHandler)
	http.HandleFunc("/api/ping", network.Ping)

	log.Printf("开始执行服务器程序")
	log.Fatal(http.ListenAndServe(":"+port, nil))
}
